package sequence

import (
	"database/sql"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

const sqlRepalceIntoStub = `REPLACE INTO sequence (stub) values ('a')`

// 建立Mysql连接 执行repalce into语句
type Mysql struct {
	conn sqlx.SqlConn
}

func NewMysql(dsn string) Sequence {
	c := sqlx.NewMysql(dsn)
	return Mysql{
		conn: c,
	}
}

// Next 取下一个号
func (m Mysql) Next() (seq uint64, err error) {
	//预处理
	var stmt sqlx.StmtSession
	stmt, err = m.conn.Prepare(sqlRepalceIntoStub)
	if err != nil {
		logx.Errorw("conn.Prepare failed ", logx.Field("err", err))
		return 0, err
	}
	defer stmt.Close()

	//执行
	var result sql.Result
	result, err = stmt.Exec()
	if err != nil {
		logx.Errorw("stmt.Exec failed ", logx.Field("err", err))
		return 0, err
	}

	//获取插入的主键id
	var lid int64
	lid, err = result.LastInsertId()
	if err != nil {
		logx.Errorw("result.LastInsertId failed ", logx.Field("err", err))
		return 0, err
	}
	return uint64(lid), nil
}
